import Loading from '../components/loading'
import api from '../libs/api'
import '../libs/promise.finally'

export default function loadingMiddleware({ dispatch, getState }) {
  return next => action => {
    const { promise, meta = { suppressLoading: false } } = action

    if (!promise) {
      return next(action)
    }

    if (!meta.suppressLoading) {
      Loading.show()
    }

    const actionPromise = promise(dispatch, getState, api)

    function finallyHandler() {
      if (!meta.suppressLoading) {
        Loading.hide()
      }
    }

    actionPromise.finally(finallyHandler)

    return next({ ...action, promise: actionPromise })
  }
}
